package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.convert.ComplaintConvert;
import com.meteor.convert.PublicityConvert;
import com.meteor.entity.Complaint;
import com.meteor.entity.Malfunction;
import com.meteor.entity.Publicity;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.ComplaintMapper;
import com.meteor.mapper.PublicityMapper;
import com.meteor.query.ComplaintQuery;
import com.meteor.query.MalfunctionQuery;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.query.PublicityQuery;
import com.meteor.service.CommunityService;
import com.meteor.service.ComplaintService;
import com.meteor.service.PublicityService;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.ComplaintVO;
import com.meteor.vo.MalfunctionVO;
import com.meteor.vo.PublicityVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class ComplaintServiceImpl extends BaseServiceImpl<ComplaintMapper, Complaint> implements ComplaintService {


    private final SystemFeign systemFeign;

    private final CommunityService communityService;


    @Override
    public void save(ComplaintVO vo) {
        Complaint  entity= ComplaintConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
            /*if(ObjectUtils.isEmpty(vo.getCommunityId())){
                OrgAndCommunityQuery query = new OrgAndCommunityQuery();
                query.setOrgId(vo.getOrgId());
                List<CommunityVO> communityVOS = communityService.orgCommunity(query);
                if(ObjectUtils.isEmpty(communityVOS)){
                    throw new ServerException("该机构下没有小区");
                }
                entity.setCommunityId(communityVOS.get(0).getId());
            }*/

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

        if(!ObjectUtils.isEmpty(vo.getImageUrls())){
            entity.setUrl(JSON.toJSONString(vo.getImageUrls()));
        }


//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(ComplaintVO complaintVO) {
        Complaint complaint = ComplaintConvert.INSTANCE.convert(complaintVO);
        if (ObjectUtils.isEmpty(complaint.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(complaint);

    }

    @Override
    public ComplaintVO getComplaint(String id) {
        return ComplaintConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<ComplaintVO> getComplaintVOList(ComplaintQuery complaintQuery) {
        List<Complaint> complaints = baseMapper.selectList(getWrapper(complaintQuery));

        return ComplaintConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<ComplaintVO> pageComplaintVO(ComplaintQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Complaint> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<ComplaintVO> list = baseMapper.getList(params);

        list.stream().forEach(t->{
            if(!ObjectUtils.isEmpty(t.getUrl())){
                t.setImageUrls(JSON.parseArray(t.getUrl(), String.class));
            }
        });
        return new PageResult<>(list, page.getTotal());

//        IPage<Complaint> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<ComplaintVO>(ComplaintConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    private Map<String, Object> getParams(ComplaintQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());
        params.put("orgId", query.getOrgId());
        params.put("merchantId", query.getMerchantId());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_complaint"));

        return params;
    }

    private Wrapper<Complaint> getWrapper(ComplaintQuery query){
        LambdaQueryWrapper<Complaint> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getContent()), Complaint::getContent, query.getContent());
        wrapper.eq(StrUtil.isNotBlank(query.getMerchantId()), Complaint::getMerchantId, query.getMerchantId());
        wrapper.eq(StrUtil.isNotBlank(query.getOrgId()), Complaint::getOrgId, query.getOrgId());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }
}
